package com.geo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * Redis配置类
 * 提供缓存管理、序列化配置和分布式数据存储功能
 * 
 * @author GEO Team
 * @version 1.0.0
 */
@Slf4j
@Configuration
@EnableCaching
@EnableRedisRepositories
public class RedisConfig {
    
    private static final Logger log = LoggerFactory.getLogger(RedisConfig.class);
    
    @Value("${spring.data.redis.timeout:5000ms}")
    private Duration timeout;
    
    /**
     * RedisTemplate配置
     * 设置序列化方式和连接配置
     */
    @Bean
    @Primary
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        
        // JSON序列化配置
        Jackson2JsonRedisSerializer<Object> jsonSerializer = jackson2JsonRedisSerializer();
        
        // String序列化配置
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        
        // 设置key和hashKey的序列化方式
        template.setKeySerializer(stringSerializer);
        template.setHashKeySerializer(stringSerializer);
        
        // 设置value和hashValue的序列化方式
        template.setValueSerializer(jsonSerializer);
        template.setHashValueSerializer(jsonSerializer);
        
        // 设置默认序列化方式
        template.setDefaultSerializer(jsonSerializer);
        template.setEnableDefaultSerializer(true);
        
        template.afterPropertiesSet();
        
        log.info("Redis模板配置完成，序列化方式：Key[String], Value[JSON]");
        return template;
    }
    
    /**
     * 字符串专用RedisTemplate
     * 用于简单的字符串操作
     */
    @Bean
    public RedisTemplate<String, String> customStringRedisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringSerializer);
        template.setValueSerializer(stringSerializer);
        template.setHashKeySerializer(stringSerializer);
        template.setHashValueSerializer(stringSerializer);
        
        template.afterPropertiesSet();
        
        log.info("Redis字符串模板配置完成");
        return template;
    }
    
    /**
     * 缓存管理器配置
     * 设置不同业务模块的缓存策略
     */
    @Bean
    @Primary
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        // 默认缓存配置
        RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1)) // 默认1小时过期
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
                .disableCachingNullValues(); // 不缓存null值
        
        // 不同业务模块的缓存配置
        Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
        
        // 用户信息缓存 - 30分钟过期
        cacheConfigurations.put("user", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        
        // 企业信息缓存 - 1小时过期
        cacheConfigurations.put("business", defaultConfig.entryTtl(Duration.ofHours(1)));
        
        // 关键词缓存 - 2小时过期
        cacheConfigurations.put("keyword", defaultConfig.entryTtl(Duration.ofHours(2)));
        
        // 内容缓存 - 30分钟过期
        cacheConfigurations.put("content", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        
        // AI模型配置缓存 - 6小时过期
        cacheConfigurations.put("aiModel", defaultConfig.entryTtl(Duration.ofHours(6)));
        
        // 监控数据缓存 - 5分钟过期
        cacheConfigurations.put("monitoring", defaultConfig.entryTtl(Duration.ofMinutes(5)));
        
        // 统计数据缓存 - 15分钟过期
        cacheConfigurations.put("statistics", defaultConfig.entryTtl(Duration.ofMinutes(15)));
        
        // 配置信息缓存 - 1天过期
        cacheConfigurations.put("config", defaultConfig.entryTtl(Duration.ofDays(1)));
        
        // 权限缓存 - 10分钟过期
        cacheConfigurations.put("permission", defaultConfig.entryTtl(Duration.ofMinutes(10)));
        
        // 热点数据缓存 - 5分钟过期
        cacheConfigurations.put("hotspot", defaultConfig.entryTtl(Duration.ofMinutes(5)));
        
        // 搜索结果缓存 - 10分钟过期
        cacheConfigurations.put("search", defaultConfig.entryTtl(Duration.ofMinutes(10)));
        
        // 临时数据缓存 - 5分钟过期
        cacheConfigurations.put("temp", defaultConfig.entryTtl(Duration.ofMinutes(5)));
        
        RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(defaultConfig)
                .withInitialCacheConfigurations(cacheConfigurations)
                .transactionAware() // 支持事务
                .build();
        
        log.info("Redis缓存管理器配置完成，共配置{}个缓存空间", cacheConfigurations.size() + 1);
        return cacheManager;
    }
    
    /**
     * Jackson2Json序列化器配置
     */
    private Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        
        // 支持Java 8时间API
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        
        serializer.setObjectMapper(objectMapper);
        return serializer;
    }
    
    /**
     * 缓存键常量定义
     */
    public static class CacheKeys {
        
        // 用户相关缓存键
        public static final String USER_INFO = "user:info:";
        public static final String USER_PERMISSIONS = "user:permissions:";
        public static final String USER_SESSION = "user:session:";
        
        // 企业相关缓存键
        public static final String BUSINESS_INFO = "business:info:";
        public static final String BUSINESS_CONFIG = "business:config:";
        public static final String BUSINESS_STATS = "business:stats:";
        
        // 关键词相关缓存键
        public static final String KEYWORD_INFO = "keyword:info:";
        public static final String KEYWORD_ANALYSIS = "keyword:analysis:";
        public static final String KEYWORD_RANKING = "keyword:ranking:";
        public static final String KEYWORD_TRENDS = "keyword:trends:";
        
        // 内容相关缓存键
        public static final String CONTENT_INFO = "content:info:";
        public static final String CONTENT_STATS = "content:stats:";
        public static final String CONTENT_SEARCH = "content:search:";
        
        // AI模型相关缓存键
        public static final String AI_MODEL_CONFIG = "ai:model:config:";
        public static final String AI_MODEL_STATS = "ai:model:stats:";
        public static final String AI_MODEL_USAGE = "ai:model:usage:";
        
        // 监控相关缓存键
        public static final String MONITORING_DATA = "monitoring:data:";
        public static final String MONITORING_ALERTS = "monitoring:alerts:";
        public static final String MONITORING_METRICS = "monitoring:metrics:";
        
        // 搜索相关缓存键
        public static final String SEARCH_RESULTS = "search:results:";
        public static final String SEARCH_SUGGESTIONS = "search:suggestions:";
        public static final String SEARCH_HISTORY = "search:history:";
        
        // 统计相关缓存键
        public static final String DAILY_STATS = "stats:daily:";
        public static final String WEEKLY_STATS = "stats:weekly:";
        public static final String MONTHLY_STATS = "stats:monthly:";
        
        // 热点数据缓存键
        public static final String HOTSPOT_CONTENT = "hotspot:content";
        public static final String HOTSPOT_KEYWORDS = "hotspot:keywords";
        public static final String HOTSPOT_TRENDS = "hotspot:trends";
        
        // 分布式锁前缀
        public static final String LOCK_PREFIX = "lock:";
        
        // 限流前缀
        public static final String RATE_LIMIT_PREFIX = "rate_limit:";
    }
    
    /**
     * 缓存过期时间定义
     */
    public static class CacheExpiration {
        public static final Duration SHORT = Duration.ofMinutes(5);
        public static final Duration MEDIUM = Duration.ofMinutes(30);
        public static final Duration LONG = Duration.ofHours(1);
        public static final Duration VERY_LONG = Duration.ofHours(6);
        public static final Duration USER_SESSION = Duration.ofHours(2);
        public static final Duration SEARCH_CACHE = Duration.ofMinutes(10);
    }
    
    /**
     * 缓存工具类
     */
    public static class CacheUtils {
        /**
         * 构建缓存键
         * @param prefix 前缀
         * @param key 键
         * @return 完整键名
         */
        public static String buildKey(String prefix, String key) {
            return prefix + key;
        }
        
        /**
         * 构建带业务ID的缓存键
         * @param prefix 前缀
         * @param businessId 业务ID
         * @param key 键
         * @return 完整键名
         */
        public static String buildBusinessKey(String prefix, String businessId, String key) {
            return prefix + businessId + ":" + key;
        }
    }
}